<template>
	<el-dialog :close-on-click-modal="false" :title="`${mode === 'add' ? '新增' : '修改'}作业计划`" width="700px" v-model="visible" @confirm="confirm"
		@cancel="closeDialog" @close="closeDialog">
		<div class="formData">
			<el-form :model="formData" ref="ruleForm" label-width="100px" :rules="rules">
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="船舶" prop="shipId">
							<RemoteSelect type="SHIP_INFO" v-model:value="formData.shipId"
							placeholder="请输入选择船舶"
								v-model:label="formData.shipName" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="航次" prop="voyage">
							<el-input v-model="formData.voyage" placeholder="请填写航次" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="贸别" prop="tradeType">
							<Select placeholder="请选择贸别" :selectData="selects.tradeType" v-model:value="formData.tradeType" :clearable="false" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="进出港" prop="inOut">
							<Select placeholder="请选择进出港" :selectData="selects.inOut" v-model:value="formData.inOut" :clearable="false" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="泊位" prop="berthId">
							<!-- <el-input v-model="formData.berthNo" placeholder="请填写泊位" /> -->
							<RemoteSelect
							  type="BERTH"
							  v-model:value="formData.berthId" v-model:label="formData.berthNo"
							  @change="selBerth"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="作业时间" prop="planTime">
							<el-date-picker v-model="formData.planTime" value-format="YYYY-MM-DD" type="date"
								placeholder="请选择计划作业时间" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="客户名称" prop="customerId">
					<RemoteSelect type="CUSTOMER_INFO" v-model:value="formData.customerId"
					placeholder="请输入客户名称"
						v-model:label="formData.customerName" />
				</el-form-item>
				<el-form-item label="作业码头" prop="dockId">
					<Select placeholder="请选择作业码头" :selectData="selects.dockList" v-model:value="formData.dockId"
						v-model:label="formData.dockName" />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="formData.remark" placeholder="请填写备注" />
				</el-form-item>
				<el-form-item label="安排拖轮">
					<el-button type="primary" @click="addTug">添加</el-button>
				</el-form-item>

				<el-form-item label="">
					<el-table :data="formData.children" :header-cell-style="{ background: '#F2F5FA' }" border
						style="width: 100%;">
						<el-table-column prop="tugNo" label="拖轮编号" width="200" />
						<el-table-column prop="workItemName" label="作业项目" />
						<el-table-column label="操作列" width="120" fixed="right" align="center">
							<template #default="scope">
								<el-popconfirm width="520" confirm-button-text="确定" cancel-button-text="取消"
									@confirm="deleteRecord(scope.row)" title="你确定要删除这条数据吗?">
									<template #reference>
										<span class="buttonFun cursor">删除</span>
									</template>
								</el-popconfirm>
							</template>
						</el-table-column>
						<template #empty>
							<el-empty v-loading="tableLoading"></el-empty>
						</template>
					</el-table>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="confirm">
					确认
				</el-button>
			</div>
		</template>
		<el-dialog :close-on-click-modal="false" v-model="visibleRecord" width="500px" :title="`安排拖轮`" append-to-body @close="closeRecordDialog">
			<div class="formData">
				<el-form :model="formDataRecord" ref="ruleFormRecord" label-width="120px" :rules="rulesRecord">
					<el-form-item label="拖轮" prop="tugId">
						<Select placeholder="请选择拖轮" :selectData="selects.tugList" v-model:value="formDataRecord.tugId"
							v-model:label="formDataRecord.tugNo" :multiple="true" :maxCollapseTags="2" />
					</el-form-item>
					<el-form-item label="作业项目" prop="workItemId">
						<Select placeholder="请选择作业项目" :selectData="selects.workItemList" v-model:value="formDataRecord.workItemId"
							v-model:label="formDataRecord.workItemName" />
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeRecordDialog">取 消</el-button>
					<el-button type="primary" @click="confirmRecord">确 认</el-button>
				</div>
			</template>
		</el-dialog>
	</el-dialog>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		defineEmits,
		defineExpose,
		nextTick
	} from "vue";
	import {
		ElMessage,
		ElMessageBox,
		ElNotification
	} from "element-plus";
	import RemoteSelect from '@/components/RemoteSelect/index.vue'
	import Select from '@/components/Select/index.vue';
	import api from '@/api/plan/plan/index';
	import tugApi from '@/api/basicData/tug';
	import workItemApi from '@/api/basicData/workItem';
	const emit = defineEmits(['callback'])
	const selects = ref({
		tradeType: [{
			label: '内贸',
			value: 'N'
		}, {
			label: '外贸',
			value: 'W'
		}],
		loadUnload: [{
			label: '装',
			value: 'Z'
		}, {
			label: '卸',
			value: 'X'
		}],
		inOut: [{
			label: '进',
			value: 'J'
		}, {
			label: '出',
			value: 'C'
		}],
		status: [{
			label: '待审',
			value: 0
		}, {
			label: '已审',
			value: 1
		}],
		tugList: [],
		workItemList: [],
		dockList: []
	})
	const tableLoading = ref(false)
	const visible = ref(false)
	const visibleRecord = ref(false);
	const ruleFormRecord = ref()
	const mode = ref('add')
	const row = ref({})
	const validateAmount = (rule, value, callback) => {
		if (!value) {
			return callback()
		}
		// 使用正则表达式校验小数点后是否只有两位  
		if (!/^-?\d+(\.\d{1,2})?$/.test(value)) {
			callback(new Error('请输入数字'));
		} else {
			// 注意：这里可能还需要进一步处理，确保末尾不是".00"之类的，但为简化示例，暂不处理  
			callback();
		}
	}
	const formData = ref({
		shipId: '',
		shipName: '',
		tradeType: 'N',
		loadUnload: 'Z',
		berthId:'',
		berthNo: '',
		planTime: '',
		frontDraft: '',
		rearDraft: '',
		customerId: '',
		customerName: '',
		inOut: 'J',
		cargoName: '',
		ton: '',
		remark: '',
		status: 0,
		portAreaCode: '04',
		portAreaName: '滨州港区',
		voyage: '',
		children: [],
		dockId: '',
		dockName: ''
	})
	const ruleForm = ref({})

	const rules = ref({
		shipId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		customerId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		portAreaCode: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		voyage: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		cargoName: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		berthId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		planTime: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		dockId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		frontDraft: [{
				required: true,
				message: '不能为空',
				trigger: 'blur'
			},
			{
				validator: validateAmount,
				trigger: 'blur'
			}
		],
		rearDraft: [{
				required: true,
				message: '不能为空',
				trigger: 'blur'
			},
			{
				validator: validateAmount,
				trigger: 'blur'
			}
		],
		ton: [{
				required: true,
				message: '不能为空',
				trigger: 'blur'
			},
			{
				validator: validateAmount,
				trigger: 'blur'
			}
		]
	})
	const formDataRecord = ref({
		tugId: [],
		tugNo: [],
		workItemId: '',
		workItemName: ''
	})
	const rulesRecord = ref({
		tugId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		workItemId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}]
	})
	// 展示
	const show = params => {
		visible.value = true
		mode.value = params?.mode || 'add'
		if (mode.value === 'edit') {
			row.value = params.row
			editInit()
		}
		getSelectList()
	}
	// 编辑
	const editInit = async () => {
		const {
			data
		} = await api.getDetailById({
			id: row.value.id
		})
		formData.value = {
			...data
		}
		// formData.value.shipId += ''
		formData.value.customerId += ''
	}
	// 确认
	const confirm = () => {
		ruleForm.value.validate(valid => {
			if (valid) {
				let request;
				if (mode.value === 'add') {
					request = api.save;
					delete formData.value.id;
				} else {
					request = api.save;
				}
				request(formData.value).then(res => {
					if (res.code == '200') {
						ElMessage.success('保存成功')
						visible.value = false;
						emit("callback");
					} else {
						ElMessage.error(res.msg)
					}
				})
			} else {
				ElMessage.warning('请完善表单信息！')
			}
		})
	}
	
	const getSelectList = () => {
		var str = '协助离泊';
		if (formData.value.inOut == 'J') str = '协助靠泊'
		selects.value.dockList = []
		selects.value.workItemList = []
		selects.value.tugList = []
		tugApi.getList({
			startPage: 1,
			pageSize: 100,
			portAreaCode: '04'
		}).then(res => {
			//判断指定作业港区下是否存在可调用拖轮
			if (res.data.records.length > 0) {
				//将已安排的拖轮id统计出来
				var selArr = formData.value.children.map(v => v.tugId)
				var par = {}
				res.data.records.forEach(item => {
					par = {
						label: item.tugNo,
						value: item.id
					}
					//判断是否是已安排的拖轮
					if (selArr.indexOf(item.id) > -1) {
						par.disabled = true;
					}
					selects.value.tugList.push(par)
				})
			}
		})
		workItemApi.getList({
			startPage: 1,
			pageSize: 100,
			workTypeCode: 1
		}).then(res => {
			if (res.data.records.length > 0) {
				res.data.records.forEach(item => {
					if (item.workItem == str) {
						formDataRecord.value.workItemId = item.id
						formDataRecord.value.workItemName = item.workItem
					}
					selects.value.workItemList.push({
						label: item.workItem,
						value: item.id
					})
				})
			}
		})
		if (formData.value.portAreaCode) {
			api.dockList({
				portAreaCode: formData.value.portAreaCode
			}).then(res => {
				if (res.data.length > 0) {
					var par = {}
					res.data.forEach(item => {
						par = {
							label: item.dockName,
							value: item.id
						}
						selects.value.dockList.push(par)
					})
				}
			})
		}
	}

	// 重置
	const closeDialog = () => {
		nextTick(() => {
			visible.value = false
			ruleForm.value.resetFields()
			formData.value.children = []
			formData.value.dockId = ''
			formData.value.dockName = ''
		})
	}
	defineExpose({
		show
	})
	
	const addTug = () => {
		getSelectList()
		visibleRecord.value = true;
		/* ruleForm.value.validate((valid) => {
			if (valid) {
				getSelectList()
				visibleRecord.value = true;
			} else {
				ElMessage.warning('表单信息填写完成后可进行拖轮安排！');
			}
		}) */
	}
	const deleteRecord = row => {
		var index = formData.value.children.indexOf(row);
		formData.value.children.splice(index, 1)
	}
	// 确认
	const confirmRecord = () => {
		ruleFormRecord.value.validate((valid) => {
			if (valid) {
				//将选择的多条数据分成一条一条的
				formDataRecord.value.tugId.forEach((item, index) => {
					formData.value.children.push({
						tugId: item,
						tugNo: formDataRecord.value.tugNo[index],
						workItemId: formDataRecord.value.workItemId,
						workItemName: formDataRecord.value.workItemName
					})
				})
				closeRecordDialog()
			} else {
				ElMessage.warning('请完善表单信息！');
			}
		})
	}
	
	// 重置
	const closeRecordDialog = () => {
		nextTick(() => {
			visibleRecord.value = false;
			ruleFormRecord.value.resetFields();
		})
	}
	
	const selBerth = (e) => {
		if(e.value){
			api.getDockBerthByBerthCode({berthCode:e.value}).then(res=>{
				if(res.data){
					formData.value.dockId = res.data.dockId
					// formData.dockName = res.data.dockName + ''
				}
			})
		}
	}
</script>